<template>
  <div class="chart-container">
    <div ref="chartRef" class="chart" v-loading="loading"></div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'
import { useModulesStore } from '@/stores/modules'
import { getCurrentTheme, getTextColor, watchThemeChange, cleanupThemeWatch } from '@/utils/theme'

const modulesStore = useModulesStore()
const chartRef = ref(null)
const loading = ref(true)
let chartInstance = null
let themeWatchers = null

// 计算图表数据
const chartData = computed(() => {
  const dashboard = modulesStore.dashboardData

  // 如果有真实的dashboard数据，使用它
  if (dashboard && dashboard.moduleTypeDistribution) {
    const distribution = dashboard.moduleTypeDistribution
    return [
      { name: '动态库', value: distribution.dylibs, itemStyle: { color: '#67C23A' } },
      { name: '框架', value: distribution.frameworks, itemStyle: { color: '#409EFF' } },
      { name: '可执行文件', value: distribution.executables, itemStyle: { color: '#E6A23C' } }
    ]
  }

  // 如果没有真实数据，使用模拟数据
  const modules = modulesStore.modules
  if (modules.length === 0) {
    return [
      { name: '动态库', value: 0, itemStyle: { color: '#67C23A' } },
      { name: '可执行文件', value: 0, itemStyle: { color: '#E6A23C' } },
      { name: '框架', value: 0, itemStyle: { color: '#409EFF' } }
    ]
  }

  const dylibs = modules.filter(m => m.name.includes('.dylib')).length
  const frameworks = modules.filter(m =>
    m.name.includes('framework') || m.name.includes('UIKit') || m.name.includes('Foundation')
  ).length
  const executables = modules.filter(m => !m.name.includes('.dylib') && !m.name.includes('framework')).length

  return [
    { name: '动态库', value: dylibs, itemStyle: { color: '#67C23A' } },
    { name: '框架', value: frameworks, itemStyle: { color: '#409EFF' } },
    { name: '可执行文件', value: executables, itemStyle: { color: '#E6A23C' } }
  ]
})

// 根据主题获取图表配置
const getChartOption = () => {
  const currentTheme = getCurrentTheme()
  const textColor = getTextColor(currentTheme)

  return {
    title: {
      text: '模块类型分布',
      left: 'center',
      top: '45%',
      textStyle: {
        fontSize: 16,
        fontWeight: 600,
        color: textColor
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
      textStyle: {
        color: '#000000',
        fontWeight: 'bold'
      },
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#333333',
      borderWidth: 1
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'center',
      textStyle: {
        color: textColor,
        fontWeight: 'bold'
      },
      data: chartData.value.map(item => item.name)
    },
    series: [
      {
        name: '模块类型',
        type: 'pie',
        radius: ['50%', '70%'],
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold',
            color: '#000000',
            borderColor: '#ffffff',
            borderWidth: 2,
            textShadowColor: '#ffffff',
            textShadowBlur: 4,
            textShadowOffsetX: 1,
            textShadowOffsetY: 1
          }
        },
        labelLine: {
          show: false
        },
        data: chartData.value
      }
    ]
  }
}

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return

  // 检查容器尺寸
  const container = chartRef.value
  if (container.clientWidth === 0 || container.clientHeight === 0) {
    // 如果容器尺寸为0，等待下一帧再试
    requestAnimationFrame(() => {
      setTimeout(() => initChart(), 100)
    })
    return
  }

  chartInstance = echarts.init(chartRef.value)
  chartInstance.setOption(getChartOption())

  // 设置主题变化监听
  themeWatchers = watchThemeChange(() => {
    if (chartInstance) {
      chartInstance.setOption(getChartOption())
    }
  })

  // 响应调整 - 使用防抖和清理
  let resizeTimer = null
  const resizeHandler = () => {
    if (resizeTimer) {
      clearTimeout(resizeTimer)
    }
    resizeTimer = setTimeout(() => {
      if (chartInstance) {
        chartInstance.resize()
      }
    }, 200) // 200ms防抖
  }

  window.addEventListener('resize', resizeHandler)

  // 在组件销毁时清理监听器
  const cleanup = () => {
    window.removeEventListener('resize', resizeHandler)
    if (resizeTimer) {
      clearTimeout(resizeTimer)
    }
  }

  // 保存清理函数到组件实例
  chartInstance.cleanup = cleanup
}

// 监听数据变化
watch(chartData, () => {
  if (chartInstance) {
    chartInstance.setOption(getChartOption())
  }
}, { deep: true })

onMounted(async () => {
  // 给一个短暂延迟确保DOM渲染完成，然后直接初始化图表
  // 不需要等待真实数据，因为我们有模拟数据
  setTimeout(() => {
    loading.value = false
    initChart()
  }, 500)
})

// 组件卸载时清理
onUnmounted(() => {
  if (themeWatchers) {
    cleanupThemeWatch(themeWatchers)
  }
  if (chartInstance) {
    // 调用保存的清理函数
    if (chartInstance.cleanup) {
      chartInstance.cleanup()
    }
    chartInstance.dispose()
    chartInstance = null
  }
})
</script>

<style scoped lang="scss">
.chart-container {
  width: 100%;
  height: 100%;
  min-height: 300px;

  .chart {
    width: 100%;
    height: 100%;
    min-height: 300px;
  }
}
</style>